package com.onlinevideo.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BaseServlet  extends HttpServlet {


    @Override
    public void init() throws ServletException {
        super.init();
        String yesterday = new SimpleDateFormat("yyyyMMdd").format(new Date(System.currentTimeMillis() - 1000 * 60 * 60 * 24));
        System.out.println("此处添加定时任务");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        if (action == null) {
            resp.getWriter().write("输入有误");
            return;
        }
        invokeActionMethod(action,req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)) {
            String action = req.getAttribute("action")!=null ?  String.valueOf(req.getAttribute("action")) : "";
            if(action.length()>0){
                invokeActionMethod(action,req,resp);
            }
        }else {
            doGet(req, resp);
        }

    }

    protected void invokeActionMethod(String action, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据action值，判断需要调用哪个方法，方法名和action值同名
        try {
            Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this, req, resp);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            String msg = "<script src='../static/js/jquery-1.11.3.min.js' type='text/javascript'></script><script src='../static/js/sweetalert.min-2.1.2.js' type='text/javascript'></script><script type='text/javascript'>$(function(){swal('警告','该链接不存在', 'error').then(function (isOk){location.href='/';});});</script>";
            req.setAttribute("msg",msg);
            req.getRequestDispatcher("/WEB-INF/view/error.jsp").forward(req,resp);
            e.printStackTrace();
        }
    }
}
